//
//  ClassCheckVC.swift
//  ZJTools
//
//  Created by 万孟超 on 2023/10/18.
//

import Cocoa

class ClassCheckVC: NSViewController {

    @IBOutlet var logTextView: NSTextView!
    @IBOutlet weak var logInfoView: NSView!
    @IBOutlet weak var projectCustomView: NSView!
    @IBOutlet weak var unusedListView: NSTableView!
    @IBOutlet weak var projectPathLabel: NSTextField!
    
    @IBOutlet weak var unusedScrollView: NSScrollView!
    var podsProject: Bool = false
    
    var logString: String = "" {
        didSet {
            Async(.main) {[self] in
                logTextView.textStorage?.setAttributedString(logString.attributedString)
                logTextView.scrollLineDown(nil)
            }
        }
    }
    
    /// .xcodeProj的路径
    var projectNamePath: String = ""
    
    var unusedClassArray: [String] = []
    
    var ignorClass: [String] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
        
        unusedScrollView.wantsLayer = true
        unusedScrollView.layer?.cornerRadius = 15
        
        projectCustomView.wantsLayer = true
        projectCustomView.layer?.cornerRadius = 15
        projectCustomView.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.3).cgColor
        
        logInfoView.wantsLayer = true
        logInfoView.layer?.cornerRadius = 15
        logInfoView.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.3).cgColor
        
    }
    
    @IBAction func developmentPodsAction(_ sender: NSSwitch) {
        podsProject = sender.state == .on
        if !projectPathLabel.stringValue.isEmpty {
            obtainPaths()
        }
    }
    
    @IBAction func chooseProjectPathAction(_ sender: NSButton) {
        File.finder(singleSelectBlock: {[weak self] path in
            self?.unusedClassArray.removeAll()
            self?.ignorClass.removeAll()
            self?.unusedListView.reloadData()
            self?.projectPathLabel.stringValue = path
            self?.logString = "路径选择成功"
            self?.obtainPaths()
        })
    }
    
    @IBAction func findUnsedClassAction(_ sender: NSButton) {
        Async(.global()) {[self] in
            logString += "\n" + "开始查找未使用的类"
            var allClassDic = File.classCheckFindReferencedFiles(projectPath: projectNamePath, progressBlock: { [weak self] fileName in
                print(fileName)
                self?.logString += "\n" + "查询：" + fileName
            }) 
            logString += "\n" + "未使用的类搜索完成"
            allClassDic.removeValue(forKey: "main")
            unusedClassArray = Array(allClassDic.keys)
            for ignore in ignorClass {
                unusedClassArray.removeObject(ignore)
            }
            Async(.main) { [self] in
                unusedListView.reloadData()
            }
        }
    }
    @IBAction func showHelp(_ sender: NSButton) {
        let alertData = ["注意！！！：工具只是辅助检查，查找出的结果可能出错!!!",
                         "！！！不要盲目清理查询出来的类",
                         "！！！根据实际情况判断是否需要清理",
                         "～功能参考Github项目：LSUnusedResources，感兴趣的可以自己去取经～",
                         "--------------------------常见场景举例----------------------------",
                         "1️⃣.例如分类",
                         "2️⃣.重写+(void)load方法的类",
                         "3️⃣.Swift扩展",
                         "4️⃣.包含C/C++方法的文件",
                         "5️⃣.开放给Module外部调用的类",
                         "----------------------------使用场景------------------------------",
                         "1️⃣.版本迭代更新/代码重构之后废弃的类",
                         "----------------------------使用说明------------------------------",
                         "1️⃣.如果当前项目是以路径导入方式创建的项目，先将Development Pods打开",
                         "2️⃣.点击Brower，选择项目的路径（clone代码时创建的文件夹）",
                         "3️⃣.选择后右边窗口会给出进度日志，等待xcodeproj路径获取成功",
                         "4️⃣.点击Search按钮，右边窗口会提示当前打印出查询日志",
                         "5️⃣.查找完成后，下面结果窗口会给出查询结果",
                         "6️⃣.单击Cell可以复制当前类的名称",
                         "7️⃣.勾选Cell再次点击查找时，可以忽略当前类，重新选择路径，重置勾选"]
        NSPopover.showPopover(alertData, of: sender)
    }
}

extension ClassCheckVC {
    func obtainPaths() {
        logString += "\n" + "正在获取.xcodeproj路径"
        projectNamePath = File.obtainXcodeProjFilePath(projectPathLabel.stringValue, isDevelopmentProject: podsProject)
        logString += "\n" + "xcodeproj路径获取成功"
    }
}

extension ClassCheckVC: NSTableViewDelegate, NSTableViewDataSource {
    func numberOfRows(in tableView: NSTableView) -> Int {
        unusedClassArray.count
    }
    
    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        var cellView = tableView.makeView(withIdentifier: .init("UnusedCellView"), owner: self) as? CellView
        if cellView == nil {
            cellView = CellView()
        }
        let classTitle = unusedClassArray[row]
        cellView?.title = unusedClassArray[row]
        cellView?.checkAction = {[weak self] isCheck in
            if isCheck {
                self?.ignorClass.append(classTitle)
            }else{
                if let index = self?.ignorClass.firstIndex(of: classTitle) {
                    self?.ignorClass.remove(at: index)
                }
            }
        }
        return cellView
    }

    func tableViewSelectionDidChange(_ notification: Notification) {
        if let table = notification.object as? NSTableView {
            let selectRow = table.selectedRow
            let pasteboard = NSPasteboard.general
            pasteboard.clearContents()
            pasteboard.setString(unusedClassArray[selectRow], forType: .string)
            if let cellView = table.view(atColumn: 0, row: selectRow, makeIfNecessary: false) {
                NSPopover.showPopover(["复制成功"], of: cellView, position: .minY)
            }
        }
    }
}
